var $util = require('../util/util');
var $sql = require('../dao/usersqlMapping');
var mq = require('mysql-queries');
var wxApiInfo = require('../conf/wxApiInfo')

module.exports = {
	getUserInfoByCode : function(req,res,next){
		var param = req.body,code = param.code;
		var https = require("https");  
		var iconv = require("iconv-lite");  
		var _self = this;
		if(!code || code.length==0){
			$util.jsonWrite(res,{success:false,code:'300',msg:'缺少code'}); 
		}else{
			var url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+wxApiInfo.appId+"&secret="+wxApiInfo.secret+"&code="+code+"&grant_type=authorization_code";  
			$util.https(url,'GET').then(function(result){
				var openid = result.openid,access_token = result.access_token,refresh_token = result.refresh_token;
				function getUserInfo(token){
					url = 'https://api.weixin.qq.com/sns/userinfo?lang=zh_CN&access_token='+token+'&openid='+openid;
					$util.https(url,'GET').then(function(result){
						mq.query($sql.findByOpenId,[openid],function(err,result){
							if(result&&result.length){
								$util.jsonWrite(res,result[0]); 
							}else{
								mq.query($sql.insert,[openid,result.nickname,result.sex,result.country,result.province,result.city,result.headimgurl],function(err,result){
									mq.query($sql.findById,[result.insertId],function(err,result){
										$util.jsonWrite(res,result[0]); 
									});
								});
							}
						});
					});
				}

				if(openid){
					url = 'https://api.weixin.qq.com/sns/auth?access_token='+access_token+'&openid='+openid;
					$util.https(url,'GET').then(function(result){
						console.log('auth',result);
						if(result.errcode==0){
							getUserInfo(access_token);
						}else{
							url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='+wxApiInfo.appId+'&grant_type=refresh_token&refresh_token=' + refresh_token;
							$util.https(url,'GET').then(function(result){
								getUserInfo(result.access_token);
							});
						}
					});
				}else{
					$util.jsonWrite(res,{success:false,code:'300',msg:'获取用户身份失败'}); 
				}
			},function(err){
				console.log(err.stack) 
				$util.jsonWrite(res,err);  
			});
		}
	},
	getUserInfoById: function(req,res,next){
		mq.query($sql.findById,[req.body.userId],function(err,result){
			$util.jsonWrite(res, result[0]);	
		});
	},
	getOrderDetail: function(req,res,next){
		mq.query($sql.getOrderById,[req.body.orderNo],function(err,result){
			$util.jsonWrite(res, result[0]);	
		});
	},
	getJsticket: function(req,res,next){
		var request = require('request'),
			cache = require('memory-cache'),
			sha1 = require('sha1'),
			url = req.body.url;

		var noncestr = ('T'+Math.random() + '').replace('.',''),
			timestamp = Math.floor(Date.now()/1000), //精确到秒
			jsapi_ticket;
		if(cache.get('ticket')){
			jsapi_ticket = cache.get('ticket');
			// console.log('1' + 'jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url);
			$util.jsonWrite(res,{
				appid:wxApiInfo.appId,
				noncestr:noncestr,
				timestamp:timestamp,
				url:url,
				jsapi_ticket:jsapi_ticket,
				signature:sha1('jsapi_ticket=' + jsapi_ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url)
			});
		}else{
			request(wxApiInfo.accessTokenUrl + '?grant_type=' + wxApiInfo.grant_type + '&appid=' + wxApiInfo.appId + '&secret=' + wxApiInfo.secret ,
				function(error, response, body){
					if (!error && response.statusCode == 200) {
						var tokenMap = JSON.parse(body);
						request(wxApiInfo.ticketUrl + '?access_token=' + tokenMap.access_token + '&type=jsapi', 
							function(error, resp, json){
								if (!error && response.statusCode == 200) {
									var ticketMap = JSON.parse(json);
									cache.put('ticket',ticketMap.ticket,wxApiInfo.cache_duration);  //加入缓存
									// console.log('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url);
									$util.jsonWrite(res,{
										appid:wxApiInfo.appId,
										noncestr:noncestr,
										timestamp:timestamp,
										url:url,
										jsapi_ticket:ticketMap.ticket,
										signature:sha1('jsapi_ticket=' + ticketMap.ticket + '&noncestr=' + noncestr + '&timestamp=' + timestamp + '&url=' + url)
									});
								}
							}
						);
					}
				}
			);
		}
	},
	updateUserInfo: function(req,res,next){
		var params = req.body;
		mq.query($sql.updateUserInfo,[params.name,params.invoice_title,params.invoice_company,params.mobile,params.id],function(err,result){
			$util.jsonWrite(res,{success:true,code:'200',msg:'操作成功！'}); 
		});
	},
};